package net.gz01.wallet.web.controller.customer;

import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;

import net.gz01.util.ZOAliSms;
import net.gz01.util.ZODate;
import net.gz01.util.ZOMD5;
import net.gz01.util.ZONumberToCN;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Account;
import net.gz01.wallet.web.model.Contacts;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.TradeOrder;
import net.gz01.wallet.web.model.YouliAccount;
import net.gz01.wallet.web.service.SendSMSConfig;

public class HomeController extends BaseController{

	public void index() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		// 今日最新3笔订单
		setAttr("orders", TradeOrder.dao.selectNewestTop(merchUser.getMerchCode(), ZODate.getDate(), 3));
		// 钱包账户
		setAttr("account", Account.dao.select(merchUser.getMerchCode()));
		render("home.html");
	}

	public void message() {
		render("message.html");
	}

	public void bill() {
		render("order.html");
	}

	public void withdraw() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		setAttr("selfBankCardList", Contacts.dao.select(merchUser.getMerchCode(), "bankCard", true));
		render("withdraw.html");
	}

	public void transfer() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		setAttr("bankCardList", Contacts.dao.select(merchUser.getMerchCode(), "bankCard", false));
		setAttr("walletList", Contacts.dao.select(merchUser.getMerchCode(), "wallet", false));
		setAttr("accountType", getPara());
		render("transfer.html");
	}

	public void preview() {
		String amount = getPara("amount");
		if(StrKit.isBlank(amount)) {
			renderFail("提款金额必填");
			return;
		}
		Contacts contacts = Contacts.dao.findById(getPara("contactsId"));
		if(contacts == null) {
			renderFail("请选择银行卡");
			return;
		}
		setAttr("tradeType", getPara("tradeType"));
		setAttr("contacts", contacts);
		setAttr("amount", amount);
		setAttr("amountInWords", ZONumberToCN.number2CNMontrayUnit(amount));
		render("preview.html");
	}

	public void chargePreview() {
		String amount = getPara("amount");
		if(StrKit.isBlank(amount)) {
			renderFail("提款金额必填");
			return;
		}
		String youliAccountId = getPara("youliAccountId");
		YouliAccount youliAccount = YouliAccount.dao.findById(youliAccountId);
		if(youliAccount == null) {
			renderFail("请选择收款银行卡");
			return;
		}
		setAttr("youliAccount", youliAccount);
		setAttr("amount", amount);
		setAttr("payer", getPara("payer"));
		setAttr("goodsName", getPara("goodsName"));
		setAttr("phoneNo", getPara("phoneNo"));
		setAttr("amountInWords", ZONumberToCN.number2CNMontrayUnit(amount));
		render("chargePreview.html");
	}

	public void orderJson() {
		// 返回数据json
		ZOSearchCondition sc = super.getSearchCondition();
		Page<TradeOrder> pageResult = TradeOrder.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void paypswd() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		if ("GET".equalsIgnoreCase(getRequest().getMethod())) {
			setAttr("type", getPara());
			render("paypswd.html");
			return;
		}
		String type = getPara("type");
		if ("update".equals(type)) {
			String oldPayPassword = ZOMD5.codeFor(getPara("oldPayPassword"));
			String payPassword = ZOMD5.codeFor(getPara("payPassword"));
			if(!oldPayPassword.equals(user.getPayPassword())) {
				renderFail("旧支付密码错误");
				return;
			}
			user.setPayPassword(payPassword);
			user.setUpdateTime(ZODate.getDateTime());
			user.update();
			renderSuccess();
			return;
		}
		if ("reset".equals(type)) {
			String code =  Redis.use().get(SendSMSConfig.SMS_PREFIX + user.getUserName());
			if(code == null){
				renderFail("短信验证码未获取或已过期");
				return;
			}
			String smscode = getPara("smscode");
			if(!code.equals(smscode)) {
				renderFail("短信验证码错误");
				return;
			}
			String payPassword = ZOMD5.codeFor(getPara("payPassword"));
			user.setPayPassword(payPassword);
			user.setUpdateTime(ZODate.getDateTime());
			user.update();
			renderSuccess();
			return;
		}
		if ("loginUpdate".equals(type)) {
			// TODO 登录密码修改
		}
		renderSuccess();		
	}
	
	public void sendsms() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		String qz = SendSMSConfig.SMS_PREFIX;
		String phoneNo = user.getUserName();
		if (phoneNo == null || phoneNo.length() < 11) {
			renderFail("手机号无效");
			return;
		}
		StringBuilder buff = new StringBuilder();
		Random rd = new Random();
		for (int i = 0; i < 6; i++) {
			buff.append(String.valueOf(rd.nextInt(10)));
		}
		String code = buff.toString();
		Redis.use().setex(qz+phoneNo, 60, code);
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("code", code);

		ZOAliSms sms = new ZOAliSms(SystemConfig.config.get("sms_accessKeyId"), SystemConfig.config.get("sms_accessSecret"));
		JSONObject result = sms.send(phoneNo, jsonObj.toJSONString(), SendSMSConfig.SMS_Name, SendSMSConfig.setPayPasswordCode);
		if ("OK".equals(result.getString("Code"))) {
			renderSuccess("验证码已发送成功");
		} else {
			renderFail(result.getString("Message"));
		}
	}
	
}
